import addOrderNoApi from '@/api/common/addOrderNoApi'
import { ToastError, ToastSuccess } from '@/util/CommonUtil'
import { Form, Modal } from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useRef, useState } from 'react'

interface ICAddOrderNo {
  addOrderNoVisible: boolean
  setAddOrderNoVisible: Dispatch<SetStateAction<boolean>>
  url: string
  idSet: (string | number)[]
  getTableData: () => void
}

export const checkIdSetErrorMsg = '请选择数据 (๑´ㅂ`๑)'

// 检查 idSet是否为空
export function checkIdSet(idSet: (string | number)[]) {
  if (!idSet || idSet.length === 0) {
    ToastError(checkIdSetErrorMsg)
    return false
  }
  return true
}

export default function CAddOrderNo(props: ICAddOrderNo) {
  const formApi = useRef<FormApi>()
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态

  return (
    <Modal
      title="加减排序号"
      visible={props.addOrderNoVisible}
      onOk={() => {
        formApi.current?.submitForm()
      }}
      onCancel={() => {
        props.setAddOrderNoVisible(false)
      }}
      maskClosable={false}
      confirmLoading={confirmLoading}
    >
      <Form
        disabled={confirmLoading}
        onSubmit={(form) => {
          if (confirmLoading) return
          setConfirmLoading(true)
          addOrderNoApi(props.url, {
            number: form.number,
            idSet: props.idSet,
          })
            .then(({ data }) => {
              ToastSuccess(data.msg)
              props.getTableData()
              setConfirmLoading(false)
              props.setAddOrderNoVisible(false)
            })
            .catch(() => {
              setConfirmLoading(false)
            })
        }}
        getFormApi={(api) => (formApi.current = api)}
      >
        <Form.InputNumber
          showClear
          className="w100"
          field="number"
          label="排序号"
          initValue={10}
          rules={[{ required: true, message: '请输入排序号' }]}
        />
      </Form>
    </Modal>
  )
}
